package stai6271;

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;

import java.net.UnknownHostException;
import java.util.Arrays;

public class MongoDbManager {
	
	static BasicDBObject query = null;
	static BasicDBObject newVal = null;
	private static long startQuery = 0;
	private static long endQuery = 0;
	
	public static MongoClient getMongoConnection(){
		
		MongoClient mongoClient = null;
		try {
			mongoClient = new MongoClient("198.199.65.41", 27017);
		} catch (UnknownHostException e) {
			System.out.println("Failed to make a connection");
			e.printStackTrace();
		}		
		return mongoClient;
	}
	
	public static void closeMongoConnection(MongoClient mc){
		mc.close();
	}
	
	public static void insertRow(DBCollection coll, String key, String lad, String id, String body, String score){
		BasicDBObject doc = new BasicDBObject("_id", key).
				append("LastActivityDate", lad).
				append("ID", id).
				append("Body", body).
				append("Score", score);
		
		coll.insert(doc);
	}
	
	public static void getRow(DBCollection coll, String fieldName, String value){
		query = new BasicDBObject(fieldName, value);
		
		
		startQuery = System.nanoTime();
		DBCursor cursor = coll.find(query);
		endQuery = System.nanoTime();
		
		System.out.println("Time of query: " + (endQuery - startQuery)/1000000 + " ms.");
		
		if(!cursor.hasNext()){
			System.out.println("no record exists.");
		}
		while(cursor.hasNext()){
			System.out.println(cursor.next());
		}
			cursor.close();
	}
	
	public static void updateRow(DBCollection coll, String key, String keyID, String fieldName, String value){
		
		newVal = new BasicDBObject();
		newVal.append("$set", new BasicDBObject().append(fieldName, value));
		query = new BasicDBObject().append(key, keyID);
				
		startQuery = System.nanoTime();
		WriteResult cursor = coll.update(query, newVal);
		endQuery = System.nanoTime();
		
		System.out.println("Time of q: " + (endQuery - startQuery)/1000000 + " ms.");
		
		System.out.println(cursor.getN());
	}
}
